package yc.gg.service.Impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import yc.gg.domain.dto.CommentDTO;
import yc.gg.domain.dto.PostDTO;
import yc.gg.domain.dto.ReplyDTO;
import yc.gg.domain.po.Post;
import yc.gg.domain.po.Reply;
import yc.gg.domain.req.CommentReq;
import yc.gg.domain.req.PostReq;
import yc.gg.domain.req.ReplyReq;
import yc.gg.mapper.PostMapper;
import yc.gg.service.IPostService;
import yc.gg.utils.Result;
import yc.gg.utils.UIDS;
import yc.gg.utils.UserHolder;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * \* User: Fuyue
 * \* Date: 2025/6/10
 * \* Description:
 * \
 */
@Service
@Slf4j
public class PostService implements IPostService {
    @Resource
    private PostMapper postMapper;

    @Override
    public Result post(PostReq postReq) {
        String topic = postReq.getTopic();
        String message = postReq.getMessage();
        if(topic == null || message == null){
            return Result.error("请输入标题或内容");
        }

        String openid = UserHolder.getUser().getOpenid();
        UIDS uid = new UIDS();
        String id = uid.GetUIDS("TZ");

        Post post = Post.builder()
                .id(id)
                .topic(topic)
                .message(message)
                .image(postReq.getImage())
                .userId(openid)
                .build();
        System.out.println(post);
        postMapper.post(post);
        return Result.success("发布成功");
    }

    @Override
    public Result get(int pageNum) {
        int pageSize = 10;
        int offset = (pageNum - 1) * pageSize;
        List<Post> posts = postMapper.get(offset,pageSize);
        return Result.success(posts);
    }

    @Override
    public Result getById(String id) {
        PostDTO postDTO = postMapper.getById(id);
        return Result.success(postDTO);
    }

    @Override
    public Result comment(CommentReq commentReq) {
        String userId = UserHolder.getUser().getOpenid();
        if(commentReq.getPostId() == null || commentReq.getContent() == null){
            return Result.error("评论失败");
        }
        UIDS uid = new UIDS();
        commentReq.setId(uid.GetUIDS("PL"));
        commentReq.setUserId(userId);
        postMapper.insertComment(commentReq);

        return Result.success("评论成功");
    }

    @Override
    public Result commentList(CommentReq commentReq) {
        String postId = commentReq.getPostId();
        int pageSize = 15;
        int offset = (commentReq.getPageNum() - 1) * pageSize;
        //查询父评论列表
        List<CommentDTO> commentDTOList = postMapper.commentList(postId, offset, pageSize);
        if (commentDTOList.isEmpty()) {
            return Result.success();
        }

        //提取父评论 ID ，批量查询子评论
        List<String> commentIds = commentDTOList.stream()
                .map(CommentDTO::getId)
                .collect(Collectors.toList());
        List<ReplyDTO> replyDTOList = postMapper.getRepliesByCommentIds(commentIds);

        //将子评论按父评论 ID 分组，然后设置到对应的 CommentDTO 中
        Map<String, List<ReplyDTO>> replyMap = replyDTOList.stream()
                .collect(Collectors.groupingBy(ReplyDTO::getCommentId));
        commentDTOList.forEach(commentDTO -> {
            commentDTO.setReplyList(replyMap.getOrDefault(commentDTO.getId(), new ArrayList<>()));
        });

        return Result.success(commentDTOList);
    }

    @Override
    public Result addReply(ReplyReq req) {
        if (req.getCommentId() == null || req.getFromUserId() == null || req.getContent() == null) {
            return Result.error("参数不能为空");
        }

        UIDS uid = new UIDS();
        String id = uid.GetUIDS("ZP");
        String openid = UserHolder.getUser().getOpenid();
        // 构建回复对象
        Reply reply = Reply.builder()
                .id(id)
                .commentId(req.getCommentId())
                .replyId(req.getReplyIdRef())
                .replyType(req.getReplyType())
                .content(req.getContent())
                .fromUserId(openid)
                .build();

        // 插入回复
        int count = postMapper.insert(reply);
        if (count > 0) {
            return Result.success("回复成功");
        }
        return Result.error("回复失败");
    }

    @Override
    public Result mine() {
        String openid = UserHolder.getUser().getOpenid();
        List<Post> list = postMapper.mine(openid);
        return Result.success(list);
    }
}